//
//  HCThirdDetailTableViewController.m
//  QuickCure1
//
//  Created by Oopsjesse on 01/11/2016.
//  Copyright © 2016 maoge. All rights reserved.
//

#import "HCThirdDetailTableViewController.h"
#import "AddillnessHistoryViewController.h"
#import "NetWorkManager.h"
#import "Disease.h"
#import "YJSearchView.h"
#import "NSString+pinyin.h"
#import "NSObject+CZRuntime.h"


@interface HCThirdDetailTableViewController ()<UITableViewDelegate,UITableViewDataSource,UISearchResultsUpdating,UISearchControllerDelegate>

@property (nonatomic, strong) NSArray<Disease *> *dataList;
@property (nonatomic, weak) UITableView *tableView;
@property (nonatomic, strong) UISearchController *searchController;
@property (nonatomic, strong) NSMutableArray<Disease *> *searchList;
@property (nonatomic, strong) NSMutableArray<NSString *> *diseaseNameList;
@end

static NSString *cellID = @"cellid";

@implementation HCThirdDetailTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"搜索疾病";
    
    [self getDataWithIndex:_index];
    
    [self setupTableView];
    
    [self setupSearchView];
}

#pragma mark -
#pragma mark - 布局搜索框
- (void)setupSearchView
{
    
    UISearchController *searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
    self.searchController = searchController;
    self.searchController.delegate = self;
    self.searchController.searchResultsUpdater = self;
    self.searchController.dimsBackgroundDuringPresentation = false;
    self.searchController.searchBar.placeholder = @"请输入搜索内容";
    [self.searchController.searchBar sizeToFit];
    
    searchController.searchBar.showsCancelButton = YES;
    UIButton *canceLBtn = [searchController.searchBar valueForKey:@"cancelButton"];
    [canceLBtn setTitle:@"取消" forState:UIControlStateNormal];
    [canceLBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    canceLBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    self.tableView.tableHeaderView = self.searchController.searchBar;
    
   
    
}



#pragma mark -
#pragma mark - 布局tableView
- (void)setupTableView
{
    UITableView *tableView = [[UITableView alloc] init];
    
    self.tableView = tableView;
    
    [self.view addSubview:tableView];
    
    [tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.edges.equalTo(self.view);
    }];
    tableView.dataSource = self;
    tableView.delegate = self;
    
    _diseaseNameList = [NSMutableArray array];
    
    [tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:cellID];
    
}


#pragma mark -
#pragma mark - 获取网络数据
-(void)getDataWithIndex:(NSInteger)index
{
    
    [[NetWorkManager sharedManager] loadDiseaseDataWithPageSize:15 ci1_id:(int)index+1 page:1 compete:^(NSArray<Disease *> *array, NSError *error) {
        
        _dataList = array;
        
        //汉字转拼音
        for (Disease * disease in array)
        {
            disease.ci3_name_pinyin = [disease.ci3_name transformToPinyin];
            disease.ci3_name_firstLetter = [disease.ci3_name transformToPinyinFirstLetter];
        }
        
        [self.tableView reloadData];
        
    }];

}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    if (!self.searchController.active)
    {
        return self.dataList.count;
    }
    return self.searchList.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID forIndexPath:indexPath];
    
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    
    if (!self.searchController.active) {
        
        cell.textLabel.text = self.dataList[indexPath.row].ci3_name;
    } else {
        cell.textLabel.text = self.searchList[indexPath.row].ci3_name;
    }
    
    return cell;
    
}

#pragma mark -
#pragma mark - 选中单元格
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    
    NSString *diseaseDetails = cell.textLabel.text;
    
    
    for (UIViewController *vc in self.navigationController.viewControllers)
    {
        if ([vc isKindOfClass:[AddillnessHistoryViewController class]])
        {
            AddillnessHistoryViewController *addVc = (AddillnessHistoryViewController *)vc;
            
            addVc.diseaseDetails = diseaseDetails;
        }
        
    }
    
    [self goBack];
}

#pragma mark -
#pragma mark - 搜索框的代理fangfa
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController {
    
    if (self.searchList.count > 0)
    {
         [self.searchList removeAllObjects];
    }
   
    NSString *key = [self.searchController.searchBar.text transformToPinyin].lowercaseString;
    
    NSMutableArray *arrayM = [NSMutableArray array];
    
    if (key.length &&key)
    {
        [self.dataList enumerateObjectsUsingBlock:^(Disease * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            NSString * name = obj.ci3_name.lowercaseString;
            NSString * namePinyin = obj.ci3_name_pinyin.lowercaseString;
            NSString * nameFirstLetter = obj.ci3_name_firstLetter.lowercaseString;
            
            NSRange rang1 = [name rangeOfString:key];
            
            if (rang1.length > 0)
            {
                [arrayM addObject:obj];
                
            }else
            {
                if ([nameFirstLetter containsString:key]) {
                    
                    [arrayM addObject:obj];
                }
                else{
                    if ([nameFirstLetter containsString:[key substringToIndex:1]]) {
                        
                        if ([namePinyin containsString:key]) {
                            [arrayM addObject:obj];
                        }
                    }
                }
            }
        }];

    }

    //遍历可变数组
    [arrayM enumerateObjectsUsingBlock:^(Disease *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        //不包含加入
        if (![self.searchList containsObject:obj]) {
            
            [self.searchList addObject:obj];
        }
        
    }];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        
        [self.tableView reloadData];
    });
}

#pragma mark -
#pragma mark - 懒加载
- (NSMutableArray<Disease *> *)searchList
{
    if (_searchList == nil)
    {
        _searchList = [NSMutableArray array];
    }
    return _searchList;
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.searchController = nil;
}

@end
